#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <string>
#include <iostream>
#include <sstream>
#include<chrono>
#include <pthread.h>

#define NUM_THREADS 24

size_t push_string(void* buffer, size_t size, size_t nmemb, void* stream)
{
    std::string data((const char*)buffer, (size_t) size * nmemb);
    *((std::stringstream*) stream) << data << std::endl;
    return size*nmemb;
}

void curl_get(std::string &http_path) {
    
    std::stringstream res_str;
    CURL *curl;
    CURLcode res;

    auto st = std::chrono::steady_clock::now();
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, http_path.c_str());
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, push_string);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &res_str);

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        /* Check for errors */
        if (res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));

        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    auto ed = std::chrono::steady_clock::now();
    std::chrono::duration<double> dur = ed - st;
    std::cout << dur.count() << "--" << res_str.str();
}

int main(int argc, char **argv)
{
    auto ss = std::chrono::steady_clock::now();
    std::string http_path;
    int count = 1;

    if (argc < 2)
    {
        printf("No url, using default url: http://10.10.9.18:8080/get?ID=object_0\n");
        http_path = "http://10.10.9.18:8080/get?ID=object_0";
    }
    else if (argc == 2)
    {
        printf("Get url: %s\n", argv[1]);
        http_path = argv[1];
    }
    else
    {
        count = atoi(argv[1]);
        http_path = argv[2];
    }
    for (size_t i = 0; i < count; i++) {
        curl_get(http_path);
    }
    
    auto ee = std::chrono::steady_clock::now();
    std::chrono::duration<double> dur = ee - ss;
    std::cout << dur.count() << std::endl;
    
    return 0;
}